package com.dayuanit.dy16.atm.controller;

import com.dayuanit.dy16.atm.dto.ResponseDTO;
import com.dayuanit.dy16.atm.handler.VoiceHandler;
import com.dayuanit.dy16.atm.service.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class MessageController extends BaseController {

    @Autowired
    private IMessageService messageService;

    @Autowired
    private VoiceHandler voiceHandler;

    @RequestMapping("/message/queryMessage")
    public ResponseDTO queryMessage(@RequestParam(required = false, defaultValue = "1") int currentPage) {
        return ResponseDTO.success(messageService.queryMessages(getUserId(), currentPage));
    }

    @RequestMapping("/message/voice.do")
    public void getVoice(String context, HttpServletResponse response) {
        logger.info("context={}", context);
        byte[] data = voiceHandler.makeVoice(context);

        response.setContentType("audio/mpeg");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(data);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/message/unReadMsg")
    public ResponseDTO unReadMsg() {
        return ResponseDTO.success(messageService.unReadMsg(getUserId()));
    }
}
